// stores/chatStore.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useChatStore = defineStore('chat', () => {
  // 聊天会话列表：key 是 targetId，value 是会话数据
  const chatSessions = ref({})

  // 获取所有会话（用于 message.vue 列表）
  const sessions = computed(() => {
    return Object.values(chatSessions.value).sort((a, b) => {
      return new Date(b.lastTime).getTime() - new Date(a.lastTime).getTime()
    })
  })

  // 添加/更新会话
  const addOrUpdateSession = (session) => {
    const { targetId, userNickname, userAvatar, lastMessage, lastTime, unreadCount = 0 } = session

    if (!chatSessions.value[targetId]) {
      // 新会话
      chatSessions.value[targetId] = {
        targetId,
        userNickname,
        userAvatar,
        lastMessage: lastMessage || '',
        lastTime: lastTime || new Date().toISOString(),
        unreadCount: 0
      }
    } else {
      // 更新已有会话
      chatSessions.value[targetId] = {
        ...chatSessions.value[targetId],
        userNickname,
        userAvatar,
        lastMessage: lastMessage || chatSessions.value[targetId].lastMessage,
        lastTime: lastTime || chatSessions.value[targetId].lastTime,
        unreadCount: unreadCount || 0
      }
    }
  }

  // 更新未读数
  const updateUnreadCount = (targetId, count) => {
    if (chatSessions.value[targetId]) {
      chatSessions.value[targetId].unreadCount = count
    }
  }

  // 清除未读数（标记为已读）
  const markAsRead = (targetId) => {
    if (chatSessions.value[targetId]) {
      chatSessions.value[targetId].unreadCount = 0
    }
  }

  // 删除会话
  const removeSession = (targetId) => {
    delete chatSessions.value[targetId]
  }

  // ✅ 持久化配置
  return {
    chatSessions,
    sessions,
    addOrUpdateSession,
    updateUnreadCount,
    markAsRead,
    removeSession
  }
}, {
  persist: {
    key: 'chat-sessions',
    storage: localStorage,
    paths: ['chatSessions'] // 只持久化 chatSessions
  }
})